package com.hdsx.netty.tomcatserver.bio;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

/**
 * @author 占贤银
 * time 2024/8/4 22:39
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class GPTomcat {

    private int port;

    private Map<String, GPServlet> handlerMappings = new HashMap<>(10);

    public int getPort() {
        return port;
    }

    public static void main(String[] args) {
        new GPTomcat().start(8080);
    }

    private void init() {
        InputStream inputStream = null;
        Properties prop = new Properties();
        try {
            // todo url -> (GPServlet)obj
            inputStream =
                    this.getClass().getClassLoader().getResourceAsStream("web.properties");
            prop.load(inputStream);
            for (Object k : prop.keySet()) {
                String key = k.toString();
                if (key.endsWith("url")) {
                    String servletName = key.replaceAll(".url$", "");
                    String url = prop.getProperty(key);
                    String className = prop.getProperty(servletName + ".className");
                    GPServlet gpServlet = (GPServlet) Class.forName(className).newInstance();
                    handlerMappings.put(url, gpServlet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void start(int port) {
        init();
        this.port = port;
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Tomcat服务已准备就绪：" + this.port);
            // 不断的轮询
            while (true) {
                // 等待客户端的请求
                Socket socket = serverSocket.accept();
                InputStream is = socket.getInputStream();
                OutputStream os = socket.getOutputStream();
                GPRequest request = new GPRequest(is);
                GPResponse response = new GPResponse(os);
                if (handlerMappings.containsKey(request.getUrl())) {
                    handlerMappings.get(request.getUrl()).service(request, response);
                } else {
                    response.write("Not Found Page！");
                }
                os.flush();
                os.close();
                is.close();
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
